//引入的组件
import CoursewareChapterTree from "@rc/pages/components/courseware-chapter-tree/index.vue";//课件章节树
import QuickScreen from "../components/quick-screen.vue";//快速筛选
import ReplaceCourseware from "../components/replace-courseware.vue";//替换课件弹窗组件
import operationLog from "../components/operation-log.vue";//操作日志弹窗组件

// 引入api
import coursewareApi from "@rc/apis/rc/courseware.mjs";


//Mixin
import Mixin from '../mixin/index.mjs';
import editMixin from '../mixin/edit.mjs';
import filtrate from './filtrate.mjs';

export default {
    name: 'rc-resource-search',
    components:{
        CoursewareChapterTree,
        QuickScreen,
        ReplaceCourseware,
        operationLog
    },
    mixins:[Mixin, editMixin],
    watch: {
        //当左侧章节科目树和上方快速搜索区域的初始化之后再去查询列表
        isInitChapterTree() {
            if(this.isInitChapterTree && this.isInitQuickList) {
                if (this.isFirstLoad === undefined) {
                    setTimeout(this.onSubmit, 1e3);
                } else {
                    this.onSubmit();
                }
                this.isFirstLoad = true;
            }
        },
        //当左侧章节科目树和上方快速搜索区域的初始化之后再去查询列表
        isInitQuickList() {
            if(this.isInitChapterTree && this.isInitQuickList) {
                if (this.isFirstLoad === undefined) {
                    setTimeout(this.onSubmit, 1e3);
                } else {
                    this.onSubmit();
                }
                this.isFirstLoad = true;
            }
        },
    },
    data() {
        return {
            pageType: 'search', // 重要：不能删除，用于混入js识别用
            /** 资源列表分页器参数*/
            resourceQueryPagination: {
                pageIndex: 0,
                pageSize: 10,
                pageCount: 0
            },
            /**资源列表 */
            resourceList: [],
            /* 列表查询加载中*/
            isShowLoading_table: false,
            isShowLoading_quick: false,
            isShowDeleteLoading: false,// 删除课件按钮
            isShowExportLoading: false,// 导出课件按钮
            // [学院id,项目id]
            projectArr: [],
            projectId:"",
            checkedKey: '',// 章节
            subjectId: '',// 科目id
            seriesCourseId:'',//系列课id
            // 快速筛选项
            quickList: [],
            isInitQuickList:false,//快速搜索区域是否初始化
            isInitChapterTree:false,// 科目树是否初始化
            dialog: {
                isShowReplaceDialog: false,//替换文件弹窗
                isShowLogDialog: false, //日志弹窗
                isShowDeleteDialog: false, //删除资源弹窗
                isShowDeleteDialogResourceTip: false,
                isShowDeleteDialogCardTip: false,
            },
            resourceId:'',//当前替换的课件id
            selectItems: [],//选择的资源
            isCheckedAll: false, //是否全选了
            /* 搜索条件 */
            filtrate: filtrate(this),
            permissArr:[],// 按钮权限控制
            pickerMinDate:'',//限制时间范围选择不能超过一年
            auditStatusObj: null,
            qualityStatusObj: null,
        };
    },
    created() {
        nlapp.PermissUtil.checkPagePermiss("rc/courseware/search-list");
        this.permissArr = this.getHasPermissArray();
        this.getQuickListInit();
        this.getAuditStatusList();
        this.getQualityStatusList();
    },
    activated() {
        if(this.isInitChapterTree && this.isInitQuickList) {
            this.permissArr = this.getHasPermissArray();
            const fromPage = this.$route.meta.fromPage;
            if(fromPage === 'relevance-detail' || fromPage === 'preview' || fromPage === 'dot') {
                this.resourceQueryPagination.pageIndex = this.$route.meta.pageIndex;
                this.onSearchResource();
            } else {
                this.onSubmit();
            }
        }
    },
    methods: {
        //获取权限
        getHasPermissArray(){
            let result = [];
            let PermissArray = [
                {
                    name:'预览',
                    permiss:'rc/courseware/search-preview',
                    eventName:'onPreview'
                },
                {
                    name:'编辑',
                    permiss:'rc/courseware/search-edit',
                    eventName:'editMixin_onEdit'
                },
                {
                    permiss:'rc/courseware/search-shelve',
                    eventName:'onShelve',
                    showCondKey:'isShelve',
                    value:{
                        'N':'上架',
                        'Y':'下架'
                    }
                },

                {
                    name:'使用详情',
                    permiss:'rc/courseware/search-detail',
                    eventName:'onResourceDetail'
                },
                {
                    name:'替换课件',
                    permiss:'rc/courseware/search-replace',
                    eventName:'onClickReplace'
                },

                {
                    name:'删除',
                    permiss:'rc/courseware/search-delete',
                    eventName:'onDelete'
                },
                {
                    name:'操作日志',
                    permiss:'rc/courseware/search-log',
                    eventName:'onSearchLog'
                },
                {
                    name:'课件打点',
                    permiss:'rc/courseware/search-dot',
                    eventName:'onVideoDots'
                },
            ];
            PermissArray.forEach(permiss=>{
                if(PermissUtil.checkPermiss(permiss.permiss)){
                    result.push(permiss);
                }
            });
            return result;
        },
        //执行点击事件
        handleClick(eventName,resource,value){
            if(eventName==='onDelete'){//删除特殊处理
                this[eventName](resource);
            } else if(eventName==='onShelve'){//上下架特殊处理
                const option = value==='Y'?'N':'Y';
                this[eventName](resource.resourceId,option);
            } else if(eventName==='onVideoDots'){//上下架特殊处理
                this[eventName](resource);
            } else {
                this[eventName](resource.resourceId);
            }
        },
        //跳转到视频打点界面
        onVideoDots(resource){
            nlapp.PageUtil.navigateToOnly('/rc/courseware/dots', {
                id: resource.resourceId,
                videoVid: resource.videoVid,
                pageIndex: this.resourceQueryPagination.pageIndex,
                resourceVideoName: resource.resourceVideoName
            });
        },
        /**
         * 资源上下架
         *  @param {String} resourceId 资源id
         *  @param {String} option 上架或下架
         */
        onShelve(resourceId,option) {
            if(option === 'Y') { // 上架
                this.shelveResource(resourceId, option);
            } else { // 下架
                const noMessage = "资源下架后,课程中心等系统不可再使用,之前已经使用过的不影响,确定下架吗?";
                this.$confirm(noMessage, '下架提醒', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.shelveResource(resourceId, option);
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消操作'
                    });
                });
            }
        },
        /**
         * 上下架
         * @param {string} resourceId  资源id
         * @param {string} option 上架或下架标识
         */
        shelveResource(resourceId,option) {
            let title = option === 'Y' ? '上架' : '下架';
            coursewareApi.shelveResource({
                data: {
                    resourceId,
                    applyScope: 'C',//Q:题 C:课 H:讲义
                    isShelve: option
                },
                success: () => {
                    this.$message.success('已'+ title );
                    this.onSubmit();
                }
            });
        },
        /**
         * 初始化快速搜索条件
         */
        getQuickListInit() {
            this.isShowLoading_quick = true;
            let quickList = [
                {
                    key: 'isShelve',
                    type: 'D',
                    placeholder:'上下架',
                    dataList: [
                        {
                            name:'全部',
                            code:''
                        },
                        {
                            name:'上架',
                            code:'Y'
                        },
                        {
                            name:'下架',
                            code:'N'
                        }
                    ]
                },
            ];
            this.quickList = quickList;
            Http.callServices([{
                    url: 'rc/admin/common/resourcetypes', //RC30001 rc/admin/common/resourcetypes课件分类
                },{
                    url: 'rc/admin/labels', // 获取标签列表
                },
            ]).success((livePlaybackState, labelsData)=>{
                quickList.push({
                    quickName:'课件分类',
                    key: 'livePlaybackState',
                    type: 'H',
                    enumData: livePlaybackState
                });
                //判断是否有资源用途标签
                if(labelsData) {
                    let resourceLable = labelsData.find(label => label.labelName === '资源用途');
                    if(resourceLable && resourceLable.labelDetailInfosResponseVoList) {
                        let enumData = resourceLable.labelDetailInfosResponseVoList.map( item =>  {
                            return {
                                name: item.labelDetailName,
                                code: item.labelDetailId
                            };
                        });
                        quickList.push({
                            quickName:'资源用途',
                            labelId: resourceLable.labelId,
                            key: 'lable'+resourceLable.labelId,
                            type: 'H',
                            isLabel: true,
                            enumData
                        });
                    }
                }
                this.quickList = quickList;
            }).complete(()=>{
                this.isShowLoading_quick = false;
            });
        },
        /**
         * 根据项目搜索年份
         */
         getYearListByProjectId() {
            this.isInitQuickList = false;
            let projectId = this.$refs.chapterTreeRef.projectId;
            this.projectId = projectId;
            this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId','');
            this.isShowLoading_quick = true;
            let quickList = this.quickList;
            Http.callServices([{
                url: 'bd/projectyear/list/simple',
                data: {
                    projectId,
                    pageIndex: 0, // 分页数据别删，否则数据可能异常
                    pageSize: 100
                }
            }]).success((yearList)=>{
                yearList = this.sortYear(yearList.data);
                yearList = yearList.map(item => ({
                    name: item.projectyearYear +'年',
                    code: item.projectyearId
                }));
                //const currentYear = new Date().getFullYear();
                const yearIndex = quickList.findIndex( item => item.key === 'applicableYearId');
                const isExists =  yearList.length > 0 ? yearList[0] : '';//yearList.find( item => item.name === currentYear + '年');
                const defaultYear = isExists ? isExists.code : '';
                this.$refs.quickScreenRef && this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId', defaultYear);
                if(yearIndex===-1) {
                    quickList.unshift({
                        quickName:'年份',
                        key: 'applicableYearId',
                        placeholder: '年份',
                        type: 'D',
                        dataList: yearList,
                        default: defaultYear
                    });
                } else {
                    quickList[yearIndex].dataList = yearList;
                    quickList[yearIndex].default =  defaultYear;
                }
                this.quickList = quickList;
            }).complete(() => {
                if(!this.isInitQuickList) {
                    this.isInitQuickList = true;
                }
                this.isShowLoading_quick = false;
            });
        },
         /**
         * 获取选中的章节，根据项目获取右侧筛选项
         * @param arr {String} 选中的章节
         */
        getCheckedKey({subjectId,chapterId,seriesCourseId}) {
            this.subjectId = subjectId;
            this.checkedKey = chapterId;
            this.seriesCourseId = seriesCourseId;
            if(this.isInitChapterTree) {
                this.onSubmit();
            }
            // 当项目变更,章节加载完成时触发查询
            this.isInitChapterTree = true;
        },
        /**
         * 获取选中的项目
         * @param projectArr
         */
        getProjectId(projectArr) {
            this.isInitChapterTree = false;
            this.projectArr = projectArr;
        },
        onSubmit() {
            this.resourceQueryPagination.pageIndex = 0;
            this.onSearchResource();
        },
        onReset() {
            setTimeout(() => {
                this.resourceQueryPagination.pageIndex = 0;
                this.onSearchResource();
            },  5e2);
        },
        /**
         * 搜索获取资源列表
         */
        onSearchResource() {
            this.isShowLoading_table = true;
            this.isCheckedAll = false;
            this.selectItems = [];

            let params = {};
            // -------拼接参数----开始
            //项目-子项目-科目-章节
            const { projectId, ptagId, subjectId, chapterId,seriesCourseId} = this.$refs.chapterTreeRef;
            if(!projectId) {
                this.$message.warning("请先选择项目");
                return;
            }
            this.resourceList = [];
            //快速搜索区域参数
            const quickList = this.quickList;
            //筛选出出星级标签的参数
            const notlableParams = quickList.filter( item => !item.isLabel);
            const lableParams = quickList.filter( item => item.isLabel);
            const quickParams = this.$refs.quickScreenRef.quickParams;
            let quickListParams = {};
            //快速搜索区域-非标签参数
            notlableParams.forEach(param => {
                quickListParams[param.key] = quickParams[param.key] || '';
            });
            //快速搜索区域-标签参数
            quickListParams.labelDetailIds = [];
            lableParams.forEach(param => {
                if( quickParams['lable' + param.labelId]) {
                    quickListParams.labelDetailIds.push(quickParams['lable'+param.labelId]);
                }
            });
            const searchParams = this.$refs.veFiltrate.getResult();
            // 处理上传时间
            console.error(searchParams);
            if(searchParams.uploadDate){
                const {start,end} = searchParams.uploadDate;
                searchParams.uploadStarTime= start?start+" 00:00:00":'';
                searchParams.uploadEndTime= end?end+" 23:59:59":'';
            }
            delete searchParams.uploadDate;
            params = {
                projectId: ptagId || projectId,//如果有子项目-就传递子项目标识
                subjectId,
                chapterId :chapterId==='ZHANGJIEAll'?'':chapterId,
                seriesCourseId,
                ...quickListParams,
                ...searchParams,
                pageIndex: PageUtil.getStartIndex(this.resourceQueryPagination),
                pageSize: this.resourceQueryPagination.pageSize,
            };
             // -------拼接参数----结束
            //调用接口
            coursewareApi.queryResourceVideoList({
                data: {
                    ...params
                },
                success: (result) => {
                    result.data.forEach((item) => {
                        item.auditStatusLabel = this.auditStatusObj ? this.auditStatusObj[item.auditStatus] : '';
                        item.qualityStatusLabel = this.qualityStatusObj ? this.qualityStatusObj[item.qualityStatus] : '';
                    });
                    this.resourceList = result.data;
                    this.$set(this.resourceQueryPagination,'pageCount', result.count);
                },
                complete:(()=>{
                    this.isShowLoading_table = false;
                })
            });
        },
        getAuditStatusList() {
            return coursewareApi.getAuditStatusList().then((res) => {
                const t = res.map((item) => {
                    return [item.code, item.name];
                });
                this.auditStatusObj = Object.fromEntries(t);
                this.resourceList.forEach((item) => {
                    item.auditStatusLabel = this.auditStatusObj ? this.auditStatusObj[item.auditStatus] : '';
                });
            });
        },
        getQualityStatusList() {
            return coursewareApi.getQualityStatusList().then((res) => {
                const t = res.map((item) => {
                    return [item.code, item.name];
                });
                this.qualityStatusObj = Object.fromEntries(t);
                this.resourceList.forEach((item) => {
                    item.qualityStatusLabel = this.qualityStatusObj ? this.qualityStatusObj[item.qualityStatus] : '';
                });
            });
        },
    }
};
